<template>
  <div ref="chartRef" style="width: 100vw; height: 400px;"></div>
</template>

<script setup lang="ts">
import { nextTick, ref, onMounted, watch,defineProps } from 'vue';
import * as echarts from 'echarts';
import { getWant } from "@/api/index";

const xValue = ref<string[]>([]);
const yValue = ref<number[]>([]);

const chartRef = ref<HTMLElement | null>(null);

// const { age } = defineProps(['want'])
// xValue.value = age.map(item => item.xValue);
// yValue.value = age.map(item => item.yValue);

// 获取数据
getWant().then(res => {
  // console.log(res.data.data.userProfile.ageRangeInfoChart.series[0].points);
  const result = res.data.data.userProfile.ageRangeInfoChart.series[0].points;
  xValue.value = result.map(item => item.xValue);
  yValue.value = result.map(item => item.yValue);
});

const option = ref({
  xAxis: {
    type: 'category',
    data: xValue.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: yValue.value,
      type: 'bar',
      lineStyle: {
        color: '#FFA500' // 设置线条颜色为橘色
      },
      itemStyle: {
        color: '#FFA500' // 设置点的颜色为橘色
      }
    }
  ]
});

// 更新图表
function updateChart() {
  if (chartRef.value !== null) {
    const myChart = echarts.getInstanceByDom(chartRef.value);
    if (myChart) {
      myChart.dispose();
    }

    const newChart = echarts.init(chartRef.value);
    newChart.setOption(option.value);
  }
}

// 监视 xValue 和 yValue 的变化，并在数据更新后重新渲染图表
watch([xValue, yValue], () => {
  if (xValue.value.length && yValue.value.length) {
    option.value = {
      xAxis: {
        type: 'category',
        data: xValue.value
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: yValue.value,
          type: 'bar',
          lineStyle: {
            color: '#FFA500' // 设置线条颜色为橘色
          },
          itemStyle: {
            color: '#FFA500' // 设置点的颜色为橘色
          } 
        }
      ]
    };

    // 数据更新后重绘图表
    updateChart();
  }
}, { immediate: true });

onMounted(() => {
  // 初始图表渲染
  if (chartRef.value !== null) {
    const myChart = echarts.init(chartRef.value);
    myChart.setOption(option.value);
  }
});
</script>

<style scoped>
/* 可以在这里添加样式，或者使用外部样式文件 */
</style>